package com.xhtt.modules.task.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.CopyUtils;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.cfg.entity.*;
import com.xhtt.modules.cfg.service.CfgTaskInfoService;
import com.xhtt.modules.cfg.service.CfgTaskSubService;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.task.dao.TaskOperPlanMapper;
import com.xhtt.modules.task.entity.TaskOperPlan;
import com.xhtt.modules.task.entity.TaskOperSeo;
import com.xhtt.modules.task.entity.TaskOperTask;
import com.xhtt.modules.task.model.oper.ArrangeModel;
import com.xhtt.modules.task.model.oper.LineModel;
import com.xhtt.modules.task.service.TaskOperPlanService;
import com.xhtt.modules.task.service.TaskOperTaskService;
import com.xhtt.modules.task.utils.StaticUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xhtt.common.utils.SerialUtils.getSerialNo;

/**
 * <p>
 * 操作计划 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-03-09
 */
@Service
public class TaskOperPlanServiceImpl extends ServiceImpl<TaskOperPlanMapper, TaskOperPlan> implements TaskOperPlanService {

    @Autowired
    private CfgTaskInfoService taskInfoService;
    @Autowired
    private CfgTaskSubService taskSubService;
    @Autowired
    private TaskOperTaskService taskOperTaskService;

    @Override
    public PageUtils planList(Map<String, Object> params, SysUserEntity user) {
        Object status = params.get("status");
        if (null != status && status.toString().equals("2"))//分配任务页面，执行班组的人可以看到安排给自己班组的任务，其他人看不到
        {
            params.put("teamId", user.getTeamId());
        }
        Page<TaskOperPlan> page = new Query<TaskOperPlan>(params).getPage();
        page.setRecords(baseMapper.planList(page, params));
        return new PageUtils(page);
    }

    @Override
    public void addPlan(TaskOperPlan taskOperPlan) {
        String noS = "CA" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        TaskOperPlan db = this.getOne(new LambdaQueryWrapper<TaskOperPlan>().likeRight(TaskOperPlan::getSerialNo, noS).orderByDesc(TaskOperPlan::getSerialNo));
        String serialNo = null == db ? "" : db.getSerialNo();
        noS = getSerialNo(noS, null == db, serialNo);
        taskOperPlan.setSerialNo(noS);
        taskOperPlan.setStatus(1);
        if (null != taskOperPlan.getLineModel() && (taskOperPlan.getType().intValue() == 2 || taskOperPlan.getType().intValue() == 4))//管线清洗
        {
            taskOperPlan.setLine(JSON.toJSONString(taskOperPlan.getLineModel()));
        }
        this.save(taskOperPlan);
    }

    @Override
    public void deletePlan(List<Integer> planIds) {
        this.removeByIds(planIds);
    }

    @Override
    public void updatePlan(TaskOperPlan taskOperPlan) {
        Integer planId = taskOperPlan.getId();
        if (null == planId) {
            throw new RRException("参数有误");
        }
        TaskOperPlan db = this.getById(planId);
        if (null == db) {
            throw new RRException("对象不存在");
        }
        CopyUtils.copyProperties(taskOperPlan, db);
        if (null != db.getLineModel() && (db.getType().intValue() == 2 || db.getType().intValue() == 4))//管线清洗
        {
            db.setLine(JSON.toJSONString(db.getLineModel()));
        }
        this.updateById(db);
    }

    @Override
    public TaskOperPlan getPlan(Integer planId) {
        return this.getById(planId);
    }

    @Override
    public ArrangeModel getArrangeInfo(Integer id) {
        ArrangeModel model = new ArrangeModel();
        TaskOperPlan taskOperPlan = this.getById(id);
        if (null == taskOperPlan) {
            throw new RRException("对象不存在");
        }

        model.setPlanId(id);
        model.setMainTaskName(taskOperPlan.getTaskName());
        List<TaskOperTask> tasks = new ArrayList<>();
        //1清罐2管线清洗3洗罐4通球99其他
        String type = "";
        if (taskOperPlan.getType().intValue() == 1) {
            type = "清罐";
        } else if (taskOperPlan.getType().intValue() == 2) {
            type = "管线清洗";
        } else if (taskOperPlan.getType().intValue() == 3) {
            type = "洗罐";
        } else if (taskOperPlan.getType().intValue() == 4) {
            type = "通球";
        } else if (taskOperPlan.getType().intValue() == 5) {
            type = "L/M作业任务";
        } else if (taskOperPlan.getType().intValue() == 6) {
            type = "入罐作业";
        } else if (taskOperPlan.getType().intValue() == 7) {
            type = "冲桶";
        } else if (taskOperPlan.getType().intValue() == 8) {
            type = "氮气置换";
        } else if (taskOperPlan.getType().intValue() == 99) {
            //说明是其他
            TaskOperTask otherTask = new TaskOperTask();
            otherTask.setName("其他");
            otherTask.setType(taskOperPlan.getType());
            tasks.add(otherTask);
            model.setTasks(tasks);
            return model;
        }
        CfgTaskInfo cfgTaskInfo = taskInfoService.getOne(new LambdaQueryWrapper<CfgTaskInfo>().eq(CfgTaskInfo::getName, type).select(CfgTaskInfo::getId));
        if (null == cfgTaskInfo) {
            throw new RRException("计划任务配置有误");
        }

        //找到配置好的要做的任务
        List<CfgTaskSub> taskSubList = taskSubService.list(new LambdaQueryWrapper<CfgTaskSub>().eq(CfgTaskSub::getTaskId, cfgTaskInfo.getId()));

        TaskOperTask operTask;
        for (CfgTaskSub cfgTaskSub : taskSubList) {
            if (cfgTaskSub.getStatus().intValue() != 1) {
                continue;//删除状态的就不管
            }
            operTask = new TaskOperTask();
            operTask.setName(cfgTaskSub.getName());
            operTask.setType(cfgTaskSub.getType());

            tasks.add(operTask);
        }
        model.setTasks(tasks);
        return model;
    }

    @Override
    @Transactional
    public void arrange(ArrangeModel arrangeModel) {
        Integer planId = arrangeModel.getPlanId();
        TaskOperPlan operPlan = this.getById(planId);
        if (null == operPlan) {
            throw new RRException("对象不存在");
        }
        operPlan.setStatus(2);//1待安排2待分配3退回4进行中9完成
        operPlan.setTaskName(arrangeModel.getMainTaskName());
        this.updateById(operPlan);//跟新个名字而已
        //
        List<TaskOperTask> tasks = arrangeModel.getTasks();
        tasks.forEach(taskShipTask -> {
            taskShipTask.setOperPlanId(planId);
            if (CollectionUtils.isNotEmpty(taskShipTask.getUserAssistModel())) {
                taskShipTask.setUserAssist(JSON.toJSONString(taskShipTask.getUserAssistModel()));
            }
        });

        //创建之前看一下有没有创建过了小任务 ，有的话全删除
        taskOperTaskService.remove(new LambdaQueryWrapper<TaskOperTask>().eq(TaskOperTask::getOperPlanId, planId));
        taskOperTaskService.saveBatch(tasks);//创建小任务
    }

    @Override
    public void back(TaskOperPlan plan) {
        TaskOperPlan op = new TaskOperPlan();
        op.setId(plan.getId());
        op.setStatus(3);//1待安排2待分配3退回4进行中9完成
        op.setBackReason(plan.getBackReason());
        this.updateById(op);
    }

    @Override
    public TaskOperSeo dataToSeo(Integer operTaskId) {
        TaskOperSeo seo = baseMapper.dataToSeo(operTaskId);
        StaticUtils.setLine(seo);
        return seo;
    }
}
